import services from '@/services/ssh';
import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import CreateForm from '@/components/CreateForm';
import EditForm, {FormValueType} from './components/EditForm';

const { page, append, deleteByIds, edit, listSSH} = services.SshInfoController;


/**
 * 新增服务器ssh连接信息
 * @param fields
 */
const handleAdd = async (fields: API.SshInfoAdd) => {
    const hide = message.loading('正在添加');
    try {
        // console.log("addFields:", fields)
        await append(fields);
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};

/**
 *  删除服务器ssh连接信息
 * @param id
 */
const handleRemove = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
        await deleteByIds([id]);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        //   message.error('删除失败，请重试');
        return false;
    }
};


/**
 * 编辑服务器ssh连接信息
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在编辑');
    try {
        console.log("fields:", fields)
        await edit({...fields} as API.SshInfoEdit);
        hide();
        message.success('编辑成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};


const TableList: React.FC<unknown> = () => {
    const actionRef = useRef<ActionType>();
    const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    // 分页
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数
    // 新增
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);


      // 列表数据接口
    const columns: ProColumns<API.SshInfo>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tooltip: '唯一的 key',
            hideInForm: true,
            hideInTable: true,
            search: false
        },
        {
            title: '服务器名',
            dataIndex: 'name',
            valueType: 'text',
            formItemProps: {
                rules: [{required: true, message: '请输入服务器名'}],
            },
        },
        {
            title: '服务账号',
            dataIndex: 'username',
            valueType: 'text',
            copyable: true,
            search: false,
            formItemProps: {
                rules: [{required: true, message: '请输入服务账号'}],
            },
        },
        {
            title: '服务器密码',
            dataIndex: 'password',
            valueType: 'password',
            ellipsis: true, // 启用文本省略
            copyable: true,
            search: false,
            formItemProps: {
                rules: [{required: true, message: '请输入服务器密码'}],
            },
        },
        {
            title: 'ssh端口',
            dataIndex: 'port',
            valueType: 'digit',
            search: false,
            initialValue: 22,
            tooltip:"常规默认都是22端口",
            formItemProps: {
                rules: [{required: true, message: '请输入ssh端口'}],
            },
        },
        {
            title: '服务器ip',
            dataIndex: 'url',
            valueType: 'text',
            formItemProps: {
                rules: [{required: true, message: '请输入服务器ip'}],
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
            valueType: 'text',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a
                        onClick={() => {
                            Modal.confirm({
                                title: '确认删除',
                                content: `确定要删除 ${record.name} 吗？`,
                                okText: '确认',
                                okType: 'danger',
                                cancelText: '取消',
                                onOk: async () => {
                                    const success = await handleRemove(record.id);
                                    ;
                                    if (success) {
                                        actionRef.current?.reloadAndRest?.();
                                    }
                                },
                            });
                        }}
                    >
                        删除
                    </a>
                    <Divider type="vertical"/>
                    <a
                        onClick={() => {
                            handleEditModalVisible(true);
                            setStepFormValues(record);
                        }}
                    >
                        编辑
                    </a>
                    <Divider type="vertical"/>
                </>
            ),
        },
    ];

    return (
        <PageContainer
            header={{
              title: '',
            }}
        >
          <ProTable<API.SshInfo>
              headerTitle=""
              actionRef={actionRef}
              rowKey="id"
              search={{
                labelWidth: 120,
              }}
              toolBarRender={() => [
                <Button
                    key="1"
                    type="primary"
                    onClick={() => handleModalVisible(true)}
                >
                  新增
                </Button>,
              ]}
              pagination={{
                current, // 当前页码
                pageSize, // 每页条数
                showSizeChanger: true, // 是否可以改变 pageSize
            pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
            onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {// pageSize 改变的回调。
              setCurrent(current);
              setPageSize(size);
            },
          }}
          // , sorter, filter
          request={async (params) => {
            const find: API.SshInfoPage  = {
              name: params.name,
              url: params.url,
              page : {
                pageIndex: params.current,
                pageSize: params.pageSize,
              },
            };
            const { data, success } = await page({
              ... find,
              // FIXME: remove @ts-ignore
              // @ts-ignore
              // sorter,
              // filter,
            });
            return {
                data: data?.rows || [],
                total: data?.total,
                pageSize: data?.pageSize,
                current: data?.currentPage,
                success,
            };
          }}
          columns={columns}
        />
        <CreateForm
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
        >
          <ProTable<API.SshInfo, API.SshInfoAdd>
            onSubmit={async (value) => {
              const success = await append(value);
              if (success) {
                handleModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="id"
            type="form"
            columns={columns}
          />
        </CreateForm>
        {stepFormValues && Object.keys(stepFormValues).length ? (
        <EditForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleEditModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onOpenChange={(visible) => {
            if (!visible) {
              handleEditModalVisible(false);
              setStepFormValues({});
            }
          }}
          editModalVisible={editModalVisible}
          values={stepFormValues}
        />
      ) : null}
      </PageContainer>
    );
};

export default TableList;
